package com.base.andlanggl.util

import android.app.ActivityManager
import android.content.Context
import android.opengl.GLES20.*
import java.lang.RuntimeException

/**
 * openGL 工具类
 */
class LangGLTools {
    companion object{
        //是否支持openGL ES 2.0版本
        fun ifSupportES2(context: Context):Boolean{
            val activityManager=context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
            val configuration=activityManager.deviceConfigurationInfo
            return configuration.reqGlEsVersion>=0x20000
        }

        fun createProgram(vertexShaderCode: String?, fragmentShaderCode: String?): Int {
            if (vertexShaderCode == null || fragmentShaderCode == null) {
                throw RuntimeException("invalid shader code")
            }
            val vertexShader = glCreateShader(GL_VERTEX_SHADER)
            val fragmentShader = glCreateShader(GL_FRAGMENT_SHADER)
            glShaderSource(vertexShader, vertexShaderCode)
            glShaderSource(fragmentShader, fragmentShaderCode)
            val status = IntArray(1)
            glCompileShader(vertexShader)
            glGetShaderiv(vertexShader, GL_COMPILE_STATUS, status, 0)
            if (GL_FALSE == status[0]) {
                throw RuntimeException(
                    "vertext shader compile,failed:" + glGetShaderInfoLog(
                        vertexShader
                    )
                )
            }
            glCompileShader(fragmentShader)
            glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, status, 0)
            if (GL_FALSE == status[0]) {
                throw RuntimeException(
                    "fragment shader compile,failed:" + glGetShaderInfoLog(
                        fragmentShader
                    )
                )
            }
            val program = glCreateProgram()
            glAttachShader(program, vertexShader)
            glAttachShader(program, fragmentShader)
            glLinkProgram(program)
            glGetProgramiv(program, GL_LINK_STATUS, status, 0)
            if (GL_FALSE == status[0]) {
                throw RuntimeException("link program,failed:" + glGetProgramInfoLog(program))
            }
            return program
        }
    }
}